# -*- coding: utf-8 -*-

import logging
import traceback

from odoo.http import request

from odoo_contrib import http as contrib_http
from odoo_contrib.parser import parse_with

from wechatpy.events import EVENT_TYPES
from wechatpy.messages import MESSAGE_TYPES

from ...schemas import parsers
from ...adaptor.factory import WechatMPFactory

logger = logging.getLogger(__name__)


@contrib_http.route('/wechat/mp')
class WechatMP(contrib_http.Controller):
    @contrib_http.route(['/gateway', '/gateway/<site>'], methods=['GET'], auth='none', type='http')
    @parse_with(parsers.mp.VerificationParser)
    def check_signature(self, **kwargs):
        site = kwargs.get('site')
        payload = self.parser.parse()
        mpapp = WechatMPFactory()[site]
        try:
            mpapp.check_signature(payload['signature'], payload['timestamp'], payload['nonce'])
        except:
            logger.error(
                'Checking signature failed. payload %s Err: %s',
                payload,
                traceback.format_exc(),
            )
            return ''
        return payload['echostr']

    @contrib_http.route(['/gateway', '/gateway/<site>'], methods=['POST'], auth='none', type='http')
    def gateway(self, **kwargs):
        try:
            site = kwargs.get('site')
            mpapp = WechatMPFactory()[site]
            payload = mpapp.parse_message(request.httprequest.data.decode('utf8'))
            logger.info('>>>>received payload type: %s', type(payload))
            if isinstance(payload, EVENT_TYPES['subscribe']):
                logger.info('>>>>sub source: %s', payload.source)
                request.env['wechat.user'].subscribe(payload.source)
            elif isinstance(payload, EVENT_TYPES['unsubscribe']):
                logger.info('>>>>unsub source: %s', payload.source)
                request.env['wechat.user'].unsubscribe(payload.source)
        except:
            pass
        return ''
